package org.dylan.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ClassLoaderUtil {
	public static URL getResource(String resourceName, Class callingClass) {
		URL url = callingClass.getResource(resourceName);
		if (url == null) {
			ClassLoader cl = callingClass.getClassLoader();
			if (cl != null)
				url = cl.getResource(resourceName);
		}
		if (url == null) {
			url = Thread.currentThread().getContextClassLoader()
					.getResource(resourceName);
		}
		if (url == null)
			url = ClassLoaderUtil.class.getClassLoader().getResource(
					resourceName);
		if (url == null
				&& resourceName != null
				&& (resourceName.length() == 0 || resourceName.charAt(0) != '/'))
			return getResource(
					(new StringBuilder()).append('/').append(resourceName)
							.toString(), callingClass);
		else
			return url;
	}

	public static InputStream getResourceAsStream(String resourceName,
			Class callingClass) {
		URL url = getResource(resourceName, callingClass);
		try {
			return url == null ? null : url.openStream();
		} catch (IOException e) {
			return null;
		}
	}
}
